package com.apps.ftapp.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.LianXiAdapter;
import com.apps.ftapp.bean.lianxi;
import com.apps.ftapp.model.LianXiModel;
import com.apps.ftapp.model.LianxiModel1;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.Tools;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;

/**
 * 题库练习
 */
public class LianXiActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.yiwancheng)
    TextView yiwancheng;
    @BindView(R.id.yiwancheng_num)
    TextView yiwanchengNum;
    @BindView(R.id.yiwancheng_num_right)
    TextView yiwanchengNumRight;
    @BindView(R.id.paihang)
    TextView paihang;
    @BindView(R.id.paihang_num)
    TextView paihangNum;
    @BindView(R.id.paihang_num_right)
    TextView paihangNumRight;
    @BindView(R.id.btn_left)
    Button btnLeft;
    @BindView(R.id.listView)
    ListView listView;
    private Gson gson = new Gson();

    private String keys = "";
    private int keycur = 0;

    private String lmname;

    String[] typeKey = {"single_choice", "choice", "uncertain_choice", "fill", "determine", "essay", "material"};
    String[] typeName = {"单选题", "多选题", "不定项选择题", "填空题", "判断题", "问答题", "材料题"};


    private CustomPopWindow mCustomPopWindow;
    private String id;

    private LianXiAdapter lianXiAdapter;
    private List<LianXiModel.ChildQuestionCategoryBean> dataList = new ArrayList();


    private List<lianxi.DataBean> typeList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lian_xi);
        ButterKnife.bind(this);


        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        id = bundle.getString("id");

        String title = bundle.getString("title");

        L.i("main", "iii::::" + id);

        setTitle(title);


        initView();

        quanbu.setOnClickListener(this);

        btnLeft.setOnClickListener(this);

        loadData(id);

    }

    /**
     * 获取课程列表
     */
    private void loadData(String id) {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("categoryId", id);
        params.put("type", Tools.isNull(keys));

        L.i("main", "token::" + Constant.token + ":::" + Constant.uid + "::cateor::" + id + ":::keys" + keys);

        Async.post("tiku/show", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    try {
                        LianXiModel result = gson.fromJson(new String(responseBody), LianXiModel.class);
                        L.i("main", "========" + Tools.isIntNull(result.getSuccess()));
                        if (1 == Tools.isIntNull(result.getSuccess())) {
                            yiwanchengNum.setText(result.getDo_questions_count() + "");

                            dataList.addAll(result.getChild_question_category());
                            lianXiAdapter.addRes(result.getChild_question_category());


                            L.i("main", "result.getDo_questions_count():====" + result.getDo_questions_count());
                            yiwanchengNum.setText(result.getDo_questions_count() + "");
                            yiwanchengNumRight.setText("/" + result.getQuestions_count() + "题");

                            paihangNum.setText(result.getMy_rank() + "");
                            paihangNumRight.setText("/" + result.getDo_sum() + "人");

                            lmname = result.getLmname();

                            L.i("main", "lmname>>@~>" + lmname);
                        }
                    } catch (Exception e) {
                        try {
                            LianxiModel1 result = gson.fromJson(new String(responseBody), LianxiModel1.class);
                            yiwanchengNum.setText(result.getDo_questions_count() + "");

                            //   dataList.addAll(result.getChild_question_category());
                            //  lianXiAdapter.addRes(result.getChild_question_category());


                            L.i("main", "result.getDo_questions_count():====" + result.getDo_questions_count());
                            yiwanchengNum.setText(result.getDo_questions_count() + "");
                            yiwanchengNumRight.setText("/" + result.getQuestions_count() + "题");

                            paihangNum.setText(result.getMy_rank() + "");
                            paihangNumRight.setText("/" + result.getDo_sum() + "人");

                            lmname = result.getLmname();
                        } catch (Exception ex) {

                        }

                    }
                }
                loadData111();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    /**
     *
     */
    private void initView() {
        quanbu.setVisibility(View.VISIBLE);
        lianXiAdapter = new LianXiAdapter(getApplicationContext(), dataList);
        listView.setAdapter(lianXiAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                HashMap<String, Object> data = new HashMap<String, Object>();
                data.put("id", dataList.get(i).getId());
                data.put("keys", keys);
                data.put("keycur", keycur);
                data.put("lmname", lmname);
                L.i("main", "keys:::" + keys);
//                ActivitySkipUtil.skipAnotherActivity(LianXiActivity.this, GestureFilpActivity.class,data);

                ActivitySkipUtil.skipAnotherActivity(LianXiActivity.this, SubjectZdTkuActivity.class, data);


//                ActivitySkipUtil.skipAnotherActivity(LianXiActivity.this, SubjectZdActivity.class,data);
            }
        });
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.btn_left:

                HashMap<String, Object> data = new HashMap<String, Object>();
                data.put("id", id);
                data.put("keys", keys);
                data.put("keycur", keycur);
                data.put("lmname", lmname);
//                ActivitySkipUtil.skipAnotherActivity(LianXiActivity.this, GestureFilpActivity.class,data);

                ActivitySkipUtil.skipAnotherActivity(LianXiActivity.this, SubjectZdActivity.class, data);

                break;

            case R.id.quanbu:
                showPopMenu();
                break;
        }
    }


    private void showPopMenu() {
//        contentView.

        LinearLayout contentView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.pop_menu, null);
//        contentView.getLayoutParams().height=typeName.length*35;

        //
        for (int i = 0; i < typeList.size(); i++) {
//            L.i("main","=======");
            TextView textView = creatText(i, typeList.get(i).getName(), typeList.get(i).getKey());
//            textView.setOnClickListener(this);
            contentView.addView(textView);
        }
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
//                .size(100,200)
//                .setBgDarkAlpha(0.7f) // 控制亮度
//                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .create()
                .showAsDropDown(quanbu, 20, 30);

    }


    /**
     *
     */
    private void loadData111() {
//        if (typeList != null && typeList.size() > 0) {
//            showPopMenu();
//
//            return;
//        }
        RequestParams params = new RequestParams();
        Async.post("tiku/questiontype", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    try {
                        lianxi result = gson.fromJson(new String(responseBody), lianxi.class);
                        if (1 == Tools.isIntNull(result.getSuccess())) {


                            if (null != result.getData() && result.getData().size() > 0) {
                                typeList = result.getData();
                                //全部
                                lianxi.DataBean qb = new lianxi.DataBean();
                                qb.setKey("");
                                qb.setName("选择");
                                typeList.add(0, qb);
                            }
                        }
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }


    /**
     * 创建一个textView，参数为文本框内容
     */
    private TextView creatText(int tag, String str, String key) {
        TextView textView = new TextView(getApplicationContext());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        textView.setLayoutParams(layoutParams);
        textView.setText(str);
        textView.setPadding(20, 0, 20, 0);
        textView.setHeight(80);
        textView.setTag(tag);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.parseColor("#444444"));
        textView.setTextSize(14);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }

                int index = (int) v.getTag();
                keys = typeList.get(index).getKey();
                quanbu.setText(typeList.get(index).getName());

                loadData(id);
            }
        });
        return textView;
    }


    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                int index = (int) v.getTag();
                L.i("min", "index:::" + index + ":::" + typeList.get(index).getKey());
                keys = typeList.get(index).getKey();

//                String showContent = "";
//                // String[] typeKey = {"single_choice","choice","uncertain_choice","fill","determine","essay","material"};
//                switch (v.getId()){
//                    case R.id.danxuanti:
//                        keys = "single_choice";
//                        keycur = 0;
////                        showContent = "点击 Item菜单1";
//                        break;
//                    case R.id.duoxuanti:
//                        keys = "choice";
//                        keycur = 1;
////                        showContent = "点击 Item菜单2";
//                        break;
//                    case R.id.budingxiang:
//                        keys = "uncertain_choice";
//                        keycur = 2;
////                        showContent = "点击 Item菜单3";
//                        break;
//                    case R.id.tiankongti:
//                        keys = "fill";
//                        keycur = 3;
////                        showContent = "点击 Item菜单4";
//                        break;
//                    case R.id.panduanti:
//                        keys = "determine";
//                        keycur = 4;
////                        showContent = "点击 Item菜单4";
//                        break;
//                    case R.id.wendati:
//                        keys = "essay";
//                        keycur = 5;
////                        showContent = "点击 Item菜单4";
//                        break;
//                    case R.id.cailiaoti:
//                        keys = "material";
//                        keycur = 6;
////                        showContent = "点击 Item菜单4";
//                        break;
//                }
//
//                quanbu.setText(typeName[keycur]);

                L.i("main", ",,,,,," + keycur);

                loadData(id);
//                Toast.makeText(LianXiActivity.this,showContent, Toast.LENGTH_SHORT).show();
            }
        };
//        contentView.findViewById(R.id.danxuanti).setOnClickListener(listener);
//        contentView.findViewById(R.id.duoxuanti).setOnClickListener(listener);
//        contentView.findViewById(R.id.budingxiang).setOnClickListener(listener);
//        contentView.findViewById(R.id.tiankongti).setOnClickListener(listener);
//        contentView.findViewById(R.id.panduanti).setOnClickListener(listener);
//        contentView.findViewById(R.id.wendati).setOnClickListener(listener);
//        contentView.findViewById(R.id.cailiaoti).setOnClickListener(listener);
    }


}
